package com.dfrz.problem.action.project;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dfrz.problem.model.Employee;
import com.dfrz.problem.model.ProjectInfo;
import com.dfrz.problem.model.User;
import com.dfrz.problem.service.EmployeeService;
import com.dfrz.problem.service.ProjectService;
import com.dfrz.problem.utils.IConstant;
import com.dfrz.problem.utils.Result;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 项目管理Action 
 * @author BIN
 *
 */
public class ProjectAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private final static Logger logger = LoggerFactory.getLogger(ProjectAction.class);
	private ProjectService projectService;
	private EmployeeService employeeService;
	private ProjectInfo projectInfo ;
	
	private User user;
    private List<ProjectInfo> listProject;
    private List<Employee> listEmployee;// 待分配员工列表
    private Map<Integer,String> mapEmployee;// 项目经理列表
    private Map<Integer,String> testEmployee;// 测试员列表
    private Map<Integer,String> workEmployee;// 开发员列表
    private List<Employee> listPlayer;
    private int selectTest;
    private int selectWork;
    private int projectId;
    private int employeeId;
    private int begin;
    private int end;
    private int page;
	private int size;
	private int pmId;
	private Employee pm;// 项目经理

    private String queryKey;// 问题查询关键字
    private String queryErro;// 查询错误提示
	
    // 获取项目经理列表
	public void putMapEmployee(){
		Result<List<Employee>> employeeList = employeeService.getEmployees();
		mapEmployee = new HashMap<Integer, String>();
		if(employeeList.getResult() != null){
			Iterator<Employee> it = employeeList.getResult().iterator();
			while(it.hasNext()){
				Employee employee = it.next();
				if(employee.getRole().getRoleId() == 2 && employee.getProject().getProjectId() == 1){
					mapEmployee.put(employee.getEmployeeId(), employee.getEmployeeName());
				}
			}
		}
	}
	
    /**
     * 新建项目
     * @return
     */
	public String addProject(){
		putMapEmployee();
		if (mapEmployee.size() <= 0) {
			queryErro = "暂无空闲项目经理管理项目！";
		}
		return SUCCESS;
	}
	
	/**
	 * 添加项目验证
	 * @return
	 */
	public String checkAddProject(){
		listProject = projectService.getAllProjects().getResult();
		Iterator<ProjectInfo> it = listProject.iterator();
		putMapEmployee();
		while(it.hasNext()){
			ProjectInfo exitedProject = it.next();
			if (this.projectInfo.getProjectName().equals(exitedProject.getProjectName())) {
				queryErro = "项目已存在";
				return INPUT;
			}
		}
		if(pmId == 0){
			queryErro = "未选择项目经理";
			return INPUT;
		}
		projectInfo.setPmId(pmId);
		projectInfo.setCreateTime(new Date());
		projectService.addProject( projectInfo);
		Employee pm = employeeService.getEmployee(pmId).getResult();
		List<Employee> list = new ArrayList<Employee>();
		list.add(pm);
		projectService.removePlayers(list,projectInfo.getProjectId());
		
		return SUCCESS;
	}
		
	/**
	 * 查询下一页
	 * @return
	 */
	public String nextPage(){
		begin = end+1;
		end = begin+9;
		size = getListProject().size();
		if(end >= size){
			end = size-1;
		}
		if(begin >= size){
			begin = size-1;
			end = begin;
		}
		page ++;
		if(page >= (size-1)/10+1){
			page = (size-1)/10+1;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 查询上一页
	 * @return
	 */
	public String prePage(){
		begin -= 10;
		if(begin <= 0){
			begin = 0;
		}
		end = begin + 9;
		if(end >= size){
			end = size-1;
		}
		page --;
		if(page <= 0){
			page = 1;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 跳转至指定页面
	 * @return
	 */
	public String toPage(){
		// 超过最大页数时跳转回首页
		if(page > size/10+1){
			page = 1;
		}
		begin = (page-1)*10;
		end = begin+9;
		if(end >= size){
			end = size-1;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 项目列表
	 * @return
	 */
	public String projectList(){
		Integer loginType = getUser().getLoginType();
		Result<List<ProjectInfo>> resultList = new Result<List<ProjectInfo>>();
		Result<Employee> result = employeeService.getEmployee(getUser().getEmail());
		if(IConstant.NOT_LOGIN.equals(result.getCode())){
			return INPUT;
		}
		if (loginType == 0) {
			resultList = projectService.getAllProjects();
		}else if(loginType == 1){
			Integer projectId = result.getResult().getProject().getProjectId();
			List<ProjectInfo> list = new ArrayList<ProjectInfo>();
			list.add( projectService.getProjectOnId(projectId).getResult());
			resultList.setResult(list);;
		}
		if(IConstant.NOT_LOGIN.equals(resultList.getCode())) {
			return INPUT;
		}
		listProject = resultList.getResult();
		// 默认每页显示10条数据
		begin = 0;
		end = 9;
		page = 1;
		size = getListProject().size();
		if(end >= size){
			end = size-1;
		}
		queryErro = "";
		
		return SUCCESS;
	}
	
	/**
	 * 添加项目成员
	 */
	public String addProjectPlayers(){
		Result<Employee> employeeRet = employeeService.getEmployee(getUser().getEmail());
		if(IConstant.NOT_LOGIN.equals(employeeRet.getCode())){
			return LOGIN;
		}
		projectInfo = projectService.getProjectOnId(employeeRet.getResult().
				getProject().getProjectId()).getResult();
		Result<List<Employee>> retListEmployee = employeeService.getNotAssign();
		listEmployee = retListEmployee.getResult();
		Iterator<Employee> it = listEmployee.iterator();
		
		testEmployee = new HashMap<Integer, String>();
		workEmployee = new HashMap<Integer, String>();
		while(it.hasNext()){
			Employee employee = it.next();
			if(employee.getRole().getRoleId() == 3){
				// 测试员
				testEmployee.put(employee.getEmployeeId(), employee.getEmployeeName());
			}else if(employee.getRole().getRoleId() == 4){
				// 开发员
				workEmployee.put(employee.getEmployeeId(), employee.getEmployeeName());
			}
		}
		
		return SUCCESS;
	}
	
	/**
	 * 查看项目成员
	 * @return
	 */
	public String playerList(){
		listPlayer = getListPlayer();
		if (listPlayer.size() == 0) {
			queryErro = "该项目还未添加成员";
		}
		// 默认每页显示10条数据
		begin = 0;
		end = 9;
		page = 1;
		size = getListPlayer().size();
		if(end >= size){
			end = size-1;
		}
		queryErro = "";
		return SUCCESS;
	}
	
	/**
	 * 项目成员移除
	 * @return
	 */
	public String playerRemove(){
		if (employeeService.getEmployee(employeeId).getResult().getRole().getRoleId() == 2) {
			queryErro = "项目经理不能删除";
		}
		projectService.removePlayer(employeeId);
		playerList();
		
//		Result<Employee> result = employeeService.getEmployee(employeeId);
//		if(IConstant.PROBLEM_NOT_EXIST.equals(result.getCode())){
//			addActionError(getText(IConstant.PROBLEM_NOT_EXIST));
//			return INPUT;
//		}
//		Employee employee = result.getResult();
//		employee.setProject(projectService.getProjectOnId(1).getResult());
//		employeeService.updateEmployee(employee);
//		playerList();
		return SUCCESS;
	}
	
	/**
	 * 添加测试员
	 * @return
	 */
	public String addTest(){
		if(selectTest == 0){
			addActionError("请选择测试员!");
			return INPUT;
		}
		Result<Employee> result = employeeService.getEmployee(selectTest);
		if(IConstant.EMPLOYEE_NOT_EXIST.equals(result.getCode())){
			addActionError(getText(IConstant.EMPLOYEE_NOT_EXIST));
			return INPUT;
		}
		Employee employee = result.getResult();
		projectInfo = projectService.getProjectOnId(projectId).getResult();
		employee.setProject(projectInfo);
		employeeService.updateEmployee(employee);
		logger.debug("新增测试员:{}",employee.getEmployeeName());
		
		return SUCCESS;
	}
	
	/**
	 * 添加开发员
	 * @return
	 */
	public String addWork(){
		if(selectWork == 0){
			addActionError("请选择开发员!");
			return INPUT;
		}
		Result<Employee> result = employeeService.getEmployee(selectWork);
		if(IConstant.EMPLOYEE_NOT_EXIST.equals(result.getCode())){
			addActionError(getText(IConstant.EMPLOYEE_NOT_EXIST));
			return INPUT;
		}
		Employee employee = result.getResult();
		projectInfo = projectService.getProjectOnId(projectId).getResult();
		employee.setProject(projectInfo);
		employeeService.updateEmployee(employee);
		logger.debug("新增开发员:{}",employee.getEmployeeName());
		
		return SUCCESS;
	}
	
	/**
	 * 项目详情
	 * @return
	 */
	public String projectDetail(){
		Result<ProjectInfo> result = projectService.getProjectOnId(projectId);
		if(IConstant.PROBLEM_NOT_EXIST.equals(result.getCode())){
			addActionError(getText(IConstant.PROBLEM_NOT_EXIST));
			return INPUT;
		}
		projectInfo = result.getResult();
		pm = employeeService.getEmployee(projectInfo.getPmId()).getResult();
		Result<List<Employee>> retList = employeeService.getListEmployee(projectInfo.getProjectId());
		
		if(!IConstant.EMPLOYEE_NOT_EXIST.equals(retList.getCode())){
			Iterator<Employee> it = retList.getResult().iterator();
			testEmployee = new HashMap<Integer, String>();
			workEmployee = new HashMap<Integer, String>();
			while(it.hasNext()){
				Employee employee = it.next();
				if(employee.getRole().getRoleId() == 3){
					// 测试员集合
					testEmployee.put(employee.getEmployeeId(), employee.getEmployeeName());
				}else if(employee.getRole().getRoleId() == 4){
					// 开发员集合
					workEmployee.put(employee.getEmployeeId(), employee.getEmployeeName());
				}
			}
		}
		
		return SUCCESS;
	}
	
	/**
	 * 关闭或打开项目
	 */
	public String openOrCloseProject() {
		projectInfo = projectService.getProjectOnId(projectId).getResult();
		projectService.closeOrOpenProject(projectInfo);
		return SUCCESS;
	}
	
	/**
	 * 删除项目
	 * @return
	 */
	public String deleteProject() {
		projectInfo = projectService.getProjectOnId(projectId).getResult();
		// 取消与该项目关联的员工
		List<Employee> list = employeeService.getListEmployee(projectId).getResult();
		projectService.deleteProject(projectInfo);
		projectService.removePlayers(list,1);
		return SUCCESS;
	}
	
	/**
	 * 修改项目
	 * @return
	 */
	public String updateProject(){
		projectInfo = projectService.getProjectOnId(projectId).getResult();
		pm = employeeService.getEmployee(projectInfo.getPmId()).getResult();
		putMapEmployee();
		if (mapEmployee.size() <= 0) {
			queryErro = "暂无空闲项目经理管理项目！";
		}
		return SUCCESS;
	}
	public String checkUpdateProject(){
//		projectInfo.setPmId(pmId);
//		projectInfo.setProjectId(projectId);
//		projectInfo.setCreateTime(projectService.getProjectOnId(projectId).getResult().getCreateTime());
//		projectService.updateProject(projectInfo);
		
		//（先将原来项目经理对应的项目改成空项目，然后把项目经理id改成新的）
		Integer oldPmId = projectInfo.getPmId();
		Employee employee = employeeService.getEmployee(oldPmId).getResult();
		employee.setProject(projectService.getProjectOnId(1).getResult());
		employeeService.updateEmployee(employee);
		
		employee = employeeService.getEmployee(pmId).getResult();
		
		projectInfo.setPmId(pmId);
		projectInfo.setProjectId(projectId);
		projectInfo.setCreateTime(projectService.getProjectOnId(projectId).getResult().getCreateTime());
		projectService.updateProject(projectInfo);
		employee.setProject(projectInfo);
		employeeService.updateEmployee(employee);
		
		return SUCCESS;
	}
	
	/**
	 * 模糊查询
	 * @return
	 */
	public String queryProject(){
		projectList();
		if (queryKey.trim().length() == 0 || queryKey == null) {
			queryErro = "请输入项目关键字!";
			return SUCCESS;
		}else {
			// 将包含查询关键字的问题保留
			Iterator<ProjectInfo> it = listProject.iterator();
			while(it.hasNext()){
				ProjectInfo projectInfo = it.next();
				if (!projectInfo.getProjectName().contains(queryKey)) {
					it.remove();
				}
			}
		}
		// 默认每页显示10条数据
		begin = 0;
		end = 9;
		page = 1;
		size = listProject.size();
		if(end >= size){
			end = size-1;
		}
		if(size == 0){
			projectList();
			queryErro = "该项目不存在!";
		}
	
//		projectList();
//		if (queryKey.trim().length() == 0 || queryKey == null) {
//			queryErro = "请输入问题关键字!";
//			return SUCCESS;
//		}else {
//			// 将包含查询关键字的问题保留
//			Iterator<ProjectInfo> it = listProject.iterator();
//			while(it.hasNext()){
//				ProjectInfo projectInfo = it.next();
//				if (projectInfo.getProjectName().contains(queryKey)) {
//					continue;
//				}else if (projectInfo.getProjectDescription().contains(queryKey)) {
//					continue;
//				}else if("开启".contains(queryKey)){
//						if (projectInfo.getProjectStatus() == 2) continue;
//						else it.remove();
//				}else if("关闭".contains(queryKey)){
//						if (projectInfo.getProjectStatus() == 1) continue;
//						else it.remove();
//				}else{
//					it.remove();
//				}
//			}
//		}
//		// 默认每页显示10条数据
//		begin = 0;
//		end = 9;
//		page = 1;
//		size = getListProject().size();
//		if(end >= size){
//			end = size-1;
//		}
//		if(listProject.size() == 0){
//			projectList();
//			queryErro = "该问题不存在!";
//		}
		
		return SUCCESS;
	}
	
	//////////////////////////////////////
	public List<ProjectInfo> getListProject() {
		listProject = projectService.getAllProjects().getResult();
		Iterator<ProjectInfo> it = listProject.iterator();
		while(it.hasNext()){
			ProjectInfo p = it.next();
			if(p.getProjectId() == 1){
				it.remove();
			}
		}
		return listProject;
	}
	public void setProjectId(int projectId) {
		this.projectId = projectId;
	}
	public void setProjectInfo(ProjectInfo projectInfo) {
		this.projectInfo = projectInfo;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getBegin() {
		return begin;
	}
	public void setBegin(int begin) {
		this.begin = begin;
	}
	public int getEnd() {
		return end;
	}
	public void setEnd(int end) {
		this.end = end;
	}
	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}
	public EmployeeService getEmployeeService() {
		return employeeService;
	}
	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}
	public ProjectInfo getProjectInfo() {
		return projectInfo;
	}
	public User getUser() {
		SessionMap<String, Object> session = (SessionMap<String, Object>) ActionContext
			.getContext().getSession();
		user = (User) session.get("user");
		return user;
	}
	
	public List<Employee> getListEmployee() {
		return listEmployee;
	}
	
	public Map<Integer, String> getWorkEmployee() {
		return workEmployee;
	}
	
	public Map<Integer, String> getTestEmployee() {
		return testEmployee;
	}
	
	public void setSelectTest(int selectTest) {
		this.selectTest = selectTest;
	}
	
	public void setSelectWork(int selectWork) {
		this.selectWork = selectWork;
	}
	
	public Map<Integer, String> getMapEmployee() {
		return mapEmployee;
	}
	
	public void setQueryKey(String queryKey) {
		this.queryKey = queryKey;
	}
	
	public String getQueryErro() {
		return queryErro;
	}
	
	public void setPmId(int pmId) {
		this.pmId = pmId;
	}
	
	public Employee getPm() {
		return pm;
	}
	
	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}
	
	public int getEmployeeId() {
		return employeeId;
	}
	
	public List<Employee> getListPlayer() {
		projectInfo = projectService.getProjectOnId(projectId).getResult();
		listPlayer = employeeService.getEmployees().getResult();
		Iterator<Employee> it = listPlayer.iterator();
		while (it.hasNext()) {
			Employee employee = it.next();
			if (employee.getProject().getProjectId() != projectId) {
				it.remove();
			}
		}
		return listPlayer;
	}
	
	public void setListPlayer(List<Employee> listPlayer) {
		this.listPlayer = listPlayer;
	}
	
	public void setMapEmployee(Map<Integer, String> mapEmployee) {
		this.mapEmployee = mapEmployee;
	}
	
	public void setPm(Employee pm) {
		this.pm = pm;
	}
	
	public int getPmId() {
		return pmId;
	}
	
}
